// 商品详情页
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    current:"1",
    price:"123",
    // 是否显示购买
    shop: false,
    // 优惠券
    coupon: [],
    // 轮播图的数量
    length:"",
    good:{},
    choose:false,
    // 是否显示加入购物车
    cart:false,
    // 选择的商品数量
    num:"",
    //显示选项卡时，获取的商品属性
    attr:[],
    // 选择的商品属性
    attrcart:[],
    // 根据属性变化的价格
    prices:"",
    // 库存
    stock:"",
    p:1,
    noMore:false,
    // make等于true时，不能点击确定按钮
    make:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var m_id = app.globalData.user.m_id;
    if (m_id == undefined) {
      app.getMid(function () {
        this.getDetail(function () {
        })
      }.bind(this))
    } else {
      this.getDetail(function () {
      })
    }
  },
  /**
   *获取商品详情
   */
  getDetail:function(callBack){
    var pages = getCurrentPages();
    var url = pages[pages.length-1];
    var p_id="";
    if (url.options.p_id){
      p_id = url.options.p_id
    }else{
      var product = app.globalData.productModel;
      p_id = product.p_id;
    }
    let that = this;
    var m_id = app.globalData.user.m_id;
    wx.request({
      url: app.globalData.yuming + 'merchant.php/Api/Product/productDetail',
      data: {
        p_id: p_id,
        m_id: m_id
      },
      header: {
        "content-type": "application/json"
      },
      success: function (res) {
        var good = res.data.data;
        var length = good.pics.length;
        that.setData({
          good: good,
          length: length
        })
        callBack();
      },
      fail: function (res) {
        wx.showModal({
          title: "提示",
          content: res.data.message,
          showCancel: false
        })
        callBack();
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getDetail(function(){
      wx.stopPullDownRefresh()
    })
   
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var info = this.data.good.p_id;
    return{
      title:this.data.good.title,
      path:"/pageA/detail/detail?p_id="+ info
    }
  },
  /**
   * 改变当前轮播图数页
   */
  changeCurrent:function(e){
    var current = e.detail.current;
    current +=1;
    this.setData({
      current:current
    })
  },
  /**
   * 加入购物车
   */
  putIntoCart:function(){
    // 获取商品属性
    var p_id = this.data.good.p_id;
    var that = this;
    var attr = that.data.attr;
    var typee = that.data.good.type;
    // 如果一开始选择过商品属性了，就不在获取了
    if(attr == "" && typee !=1 ){
      var prices = this.data.good.price;
      wx.request({
        url: app.globalData.yuming + 'merchant.php/Api/Product/productAttr',
        data: {
          p_id: p_id
        },
        header: {
          "content-type": "application/json"
        },
        success: function (res) {
          attr = res.data.data;
          // 显示选项卡
          var cart = !that.data.cart;
          var num = 1;
          var stock = that.data.good.stock;
          that.setData({
            cart: cart,
            num: num,
            attr: attr,
            prices: prices,
            stock: stock
          })
          
        },
        fail: function (res) {
          wx.showModal({
            title: '提示',
            content: res.data.message,
            showCancel: false
          })
        }
      })
    }else if(typee !=1){
      var stock = that.data.stock;
      var num = this.data.num;
      var cart = !this.data.cart;
      this.setData({
        stock:stock,
        num: num,
        cart: cart
      })
    }else{
      var stock = that.data.good.stock;
      var prices= that.data.good.price;
      var num = this.data.num;
      if(num == ""){
        num =1
      }
      var cart = !this.data.cart;
      this.setData({
        stock: stock,
        num: num,
        cart: cart,
        prices: prices
      })
    }
    
   
   
    
  },
  /**
   * 选择属性
   */
  checked:function(e){
    var that = this;
    var p_id = this.data.good.p_id;
    var val_id = e.currentTarget.dataset.index;
    var attr = this.data.attr;
    // 获取商品属性串
    var attrcart = this.data.attrcart;
    // 同一个属性，只能选择一个属性值
    for(var i=0,length=attr.length;i<length;i++){
      var item = attr[i].attr_val;
      for(var j=0,l=item.length;j<l;j++){
        if(item[j].val_id == val_id){
          
          for(var n=0;n<l;n++){
           var v_id =  item[n].val_id;
            for(var p=0,m=attrcart.length;p<=m;p++){
              if(attrcart[p]==v_id){
                attrcart.splice(p, 1)
              }
            }
            item[n]['checked']=false;
          }
          item[j]['checked'] = true;
        }
      }
    }
    attrcart.push(val_id);
    attrcart.sort()
    // 判断全部属性都已经选择了以后，请求当前属性对应的价格和库存
    if(attrcart.length == attr.length){
      var att = attrcart[0];
      for (var i = 1, length = attrcart.length; i < length; i++) {
        att = att + "|" + attrcart[i];
      }
      // 获取当前属性的价格和库存
      wx.request({
        url: app.globalData.yuming + 'merchant.php/Api/Product/productPrice',
        data:{
          p_id:p_id,
          attr: att
        },
        header:{
          "content-type":"application/x-www-form-urlencoded"
        },
        method:"POST",
        success:function(res){
            var prices = res.data.data.price;
            var stock = res.data.data.stock;
            if(stock == 0){
              wx.showModal({
                title: '提示',
                content: '库存为0',
                showCancel: false,
                success: function () {
                  that.setData({
                    stock: 0
                  })
                }
              })
            }else{
              that.setData({
                prices:prices,
                stock:stock
              })
            }
        },
        fail:function(res){
          wx.showModal({
            title: '提示',
            content: res.data.message,
            showCancel:false
          })
        }
      })
    }
    that.setData({
      attrcart: attrcart.sort(),
      attr: attr
    })
  },
 /**
  * 关闭购物车选项卡
  */
 closeCart:function(){
   // 显示选项卡
   var cart = !this.data.cart;
   this.setData({
     cart: cart
   })
 },
  /**
   * 确定加入购物车
   */
  goshopCart:function(){
    
    var that = this;
    var m_id = app.globalData.user.m_id;
    var shop_id = this.data.good.shop_id;
    var p_id = this.data.good.p_id;
    var num = this.data.num;
    var attrcart = this.data.attrcart;
    var attr = attrcart[0];
    var typee = this.data.good.type;
    // 判断商品属性是否选择完全
    for(var i=1,length=attrcart.length;i<length; i++){
      attr = attr + "|" + attrcart[i];
    }
    if (typee != 1) {
      var attrA = that.data.attr;
      for(var j=0,l=attrA.length;j<l;j++){
        var val = attrA[j];
        var a = 0;
        for(var m=0,ll=val.attr_val.length;m<ll;m++){
          for (var i = 0, length = attrcart.length;i<length;i++){
            if (val.attr_val[m].val_id == attrcart[i]){
              a = a + 1;
             }else{
               a = a + 0;
             }
          }
        }
        if (a == 0) {
          wx.showModal({
            title: '提示',
            content: "请选择" + val.attr_name.attr_name,
            showCancel: false
          })
          console.log(val.attr_name.attr_name)
          return;
        }
      }
      this.setData({
        make: true
      })
    var price = this.data.prices;
// 请求库存量，如果库存为0，提示库存不足，如果不为0，添加购物车
    wx.request({
      url: app.globalData.yuming + 'merchant.php/Api/Product/productPrice',
      data:{
          p_id:p_id,
          attr:attr
      },
      header:{
      "content-type":"application/x-www-form-urlencoded"
      },
      method:"POST",
      success:function(res){
        var stock = res.data.data.stock;
        price = res.data.data.price
        if(stock !=0){
          wx.request({
            url: app.globalData.yuming + 'merchant.php/Api/Cart/addCart',
            data: {
              m_id: m_id,
              shop_id: shop_id,
              p_id: p_id,
              num: num,
              attr: attr,
              price: price
            },
            header: {
              "content-type": "application/x-www-form-urlencoded"
            },
            method: "POST",
            success: function (res) {
              that.setData({
                make: false
              })
              wx.showToast({
                title: res.data.message,
                image: "../../images/success.png",
                success: function () {
                  var cart = !that.data.cart;
                  setTimeout(function () {
                    that.setData({
                      cart: cart
                    })
                  }, 500)

                }
              })

            }.bind(this),
            fail: function (res) {
              this.setData({
                make: false
              })
              wx.showModal({
                title: '提示',
                content: res.data.message,
                showCancel: false
              })
            }.bind(this)
          })
        }else{
          wx.showModal({
            title: '提示',
            content: '库存不足！',
            showCancel:false,
            success:function(){
              that.setData({
                make: false
              })
            }.bind(this)
          })
          
        }
      },
      fail:function(res){
        wx.showModal({
          title: '提示',
          content: res.data.message,
        })
      }
    })
    } else {
      attr =""
      var price = this.data.prices;
      wx.request({
        url: app.globalData.yuming + 'merchant.php/Api/Cart/addCart',
        data: {
          m_id: m_id,
          shop_id: shop_id,
          p_id: p_id,
          num: num,
          attr: attr,
          price: price
        },
        header: {
          "content-type": "application/x-www-form-urlencoded"
        },
        method: "POST",
        success: function (res) {
          wx.showToast({
            title: res.data.message,
            image: "../../images/success.png",
            success: function () {
              var cart = !that.data.cart;
              setTimeout(function () {
                that.setData({
                  cart: cart
                })
              }, 500)

            }
          })

        },
        fail: function (res) {
          wx.showModal({
            title: '提示',
            content: res.data.message,
            showCancel: false
          })
        }
      })
    }
  },
  /**
   * 选择优惠券
   */
  chooseCoupon:function(){
    var that = this;
    var shop_id = this.data.good.shop_id;
    var m_id = app.globalData.user.m_id;
    var p =1;
    wx.request({
      url: app.globalData.yuming + 'merchant.php/Api/Coupon/couponShopList',
      data:{
        shop_id:shop_id,
        p:p,
        m_id:m_id
      },
      header:{
        "content-type":"application/x-www-form-urlencoded"
      },
      method:"POST",
      success:function(res){
        console.log(res)
        var coupon = res.data.data;
        that.setData({
          coupon:coupon
        })
      }
    })
    var choose = this.data.choose;
    this.setData({
      choose: !choose
    })
  },
  /**
   * 下拉分页优惠券
   */
  most:function(){
    var noMore = this.data.noMore;
    var coupon = this.data.coupon;
    if(noMore == false){
      var that = this;
      var shop_id = this.data.good.shop_id;
      var m_id = app.globalData.user.m_id;
      var p = this.data.p;
      p = p + 1;
      wx.request({
        url: app.globalData.yuming + 'merchant.php/Api/Coupon/couponShopList',
        data: {
          shop_id: shop_id,
          p: p,
          m_id: m_id
        },
        header: {
          "content-type": "application/x-www-form-urlencoded"
        },
        method: "POST",
        success: function (res) {
          var cou = res.data.data;
          if (cou != "") {
            coupon.push(cou)
          } else {
            noMore = true
          }
          that.setData({
            coupon: coupon,
            noMore: noMore
          })
        }
      })
    }
    
  },
  /**
   * 领取优惠拳
   */
  receive:function(e){
    var that = this;
    var shop_id = this.data.good.shop_id;
    var m_id = app.globalData.user.m_id;
    var p = 1;
    var coupon_id = e.currentTarget.dataset.id;
    wx.request({
      url: app.globalData.yuming + 'merchant.php/Api/Coupon/getCou',
      data:{
        m_id:m_id,
        coupon_id:coupon_id
      },
      header:{
        "content-type":"application/x-www-form-urlencoded"
      },
      method:"POST",
      success:function(res){
        wx.showModal({
          title: "提示",
          content: res.data.message,
          showCancel: false,
          // 领取成功后，刷新优惠券列表
          success:function(){
            
            wx.request({
              url: app.globalData.yuming + 'merchant.php/Api/Coupon/couponShopList',
              data: {
                shop_id: shop_id,
                p: p,
                m_id: m_id
              },
              header: {
                "content-type": "application/x-www-form-urlencoded"
              },
              method: "POST",
              success: function (res) {
                console.log(res)
                var coupon = res.data.data;
                that.setData({
                  coupon: coupon
                })
              }
            })
          }
        })
      },
      fail:function(res){
        wx.showModal({
          title:"提示",
          content:res.data.message,
          showCancel:false
        })
      }
    })
  },
  /**
   * 选择优惠券完成
   */
  complate:function(){
    var choose = this.data.choose;
    this.setData({
      choose: !choose
    })
  },
  /**
   * 立即购买
   */
  goshoping:function(){
    // 获取商品属性
    var p_id = this.data.good.p_id;
    var that = this;
    var attr = that.data.attr;
    var prices = this.data.good.price;
    // 虚拟商品的typee = 1,虚拟商品不需要选择属性
    var typee = this.data.good.type;
    // 如果一开始选择过商品属性了，就不在获取了
    if (attr == "" && typee!=1) {
      wx.request({
        url: app.globalData.yuming + 'merchant.php/Api/Product/productAttr',
        data: {
          p_id: p_id
        },
        header: {
          "content-type": "application/json"
        },
        success: function (res) {
          attr = res.data.data
          // 显示选项卡
          var shop = !that.data.shop;
          var num = 1;
          var stock = that.data.good.stock;
          that.setData({
            attr: attr,
            num: num,
            shop: shop,
            stock:stock,
            prices:prices
          })

        },
        fail: function (res) {
          wx.showModal({
            title: '提示',
            content: res.data.message,
            showCancel: false
          })
        }
      })
    }else if(typee != 1){
      var num = this.data.num;
      var shop = !this.data.shop;
      this.setData({
        num: num,
        shop: shop
      })
    }else{
      var stock = that.data.good.stock;
      var prices = that.data.good.price;
      var num = this.data.num;
      if (num == "") {
        num = 1
      }
      var shop = !this.data.shop;
      this.setData({
        num: num,
        shop: shop,
        prices: prices,
        stock: stock
      })
    }
    
  },
  /**
   * 确定购买
   */
  gochar:function(){
    var that = this;
    var typee = this.data.good.type;
    // 获取请求时需要的数据，放在缓存里
    var shop_id = this.data.good.shop_id;
    if (typee != 1){
      var stock = this.data.stock;
      if(stock == 0){
        wx.showModal({
          title: '提示',
          content: '库存为0',
          showCancel:false
        })
        return;
      }else{
        var attrcart = this.data.attrcart;
        var attr = attrcart[0];
        for (var i = 1, length = attrcart.length; i < length; i++) {
          attr = attr + "|" + attrcart[i];
        }
        var attrA = that.data.attr;
        for (var j = 0, l = attrA.length; j < l; j++) {
          var val = attrA[j];
          var a = 0;
          for (var m = 0, ll = val.attr_val.length; m < ll; m++) {
            for (var i = 0, length = attrcart.length; i < length; i++) {
              if (val.attr_val[m].val_id == attrcart[i]) {
                a = a + 1;
              } else {
                a = a + 0;
              }
            }
          }
          if (a == 0) {
            wx.showModal({
              title: '提示',
              content: "请选择" + val.attr_name.attr_name,
              showCancel: false
            })
            console.log(val.attr_name.attr_name)
            return;
          }
        }
      }
      
    }else{
      attr = ""
    }
    this.setData({
      make: true
    })
    var p_id = this.data.good.p_id;
    var num = this.data.num;
    var storage = [0, shop_id, p_id,attr,num]
    wx.setStorage({
      key: 'storage',
      data: storage,
      success:function(res){
        // 先关闭选项卡
        var shop = that.data.shop;
        that.setData({
          shop: !shop,
          make:false
        })
        // 跳转页面
        wx.navigateTo({
          url: '/order/orderlist/orderlist',
        })
      },
      that:function(res){
        this.setData({
          make: false
        })
        wx.showModal({
          title: '提示',
          content: "貌似出了点问题",
        })
      }
    })
   
  },
  /**
   * 收藏/取消收藏    
   */
  changeCollection:function (url){
    var that = this;
    var goods_id = this.data.good.p_id;
    var m_id = app.globalData.user.m_id;
    var good = that.data.good;
    wx.request({
      url: app.globalData.yuming + url,
      data: {
        goods_id: goods_id,
        m_id: m_id
      },
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      method: "POST",
      success: function (res) {
        if (good.is_collect == 0){
          good.is_collect = 1
        }else{
          good.is_collect = 0
        }
        that.setData({
          good: good
        })
      },
      fail: function (res) {
        wx.showModal({
          title: "提示",
          content: res.data.message,
          showCancel: false
        })
      }
    })
  },
  // 收藏/取消
  Collection:function(){
    let that = this;
    var is_collect = that.data.good.is_collect;
    if(is_collect == 0){
      let url = "merchant.php/Api/Member/collect";
      that.changeCollection(url)
    }else{
      let url = "merchant.php/Api/Member/cancelCollect";
      that.changeCollection(url)
    }
   
  },
  /**
   * 返回首页
   */
  homepage: function () {
      wx.switchTab({
        url: '/pages/shouye/shouye',
      })
  },
  /**
   * 加号
   */
  buyAdd:function(){
    var num = this.data.num;
    var stock = this.data.stock;
    if(num >= stock){
      wx.showModal({
        title: '提示',
        content: '库存不足',
        showCancel: false
      })
    }else{
      num += 1;
    }
    this.setData({
      num:num
    })
  }, 
  /**
   * 减号
   */
  buyMini: function () {
    var num = this.data.num;
    var stock = this.data.stock;
    if(num == 1){
      wx.showModal({
        title: '提示',
        content: '不能少于一件',
        showCancel:false
      })
    }else{
      if (num > stock){
        wx.showModal({
          title: '提示',
          content: '库存:'+stock, 
          showCancel: false
        })
        num = Number(stock)
      }else{
        num = num - 1;
      }
    
      this.setData({
        num: num
      })
    }
   
  },
  /**
   * 查看商品的全部评价
   */
  more:function(){
   wx.navigateTo({
     url: '/pageA/comment/comment',
   })
  },
  /**
   * 猜你喜欢的商品详情
   */
  detail:function(e){
    var index = e.currentTarget.dataset.index;
    var good = this.data.good.goods_list[index];
    app.globalData.productModel = good;
    wx.redirectTo({
      url: '/pageA/detail/detail',
    })
  }
})